//
//  HTTPHelper.m
//  qianke
//
//  Created by ZX on 2017/6/23.
//  Copyright © 2017年 ZX. All rights reserved.
//

#import "HTTPHelper.h"
#import "AFNetworking.h"
@implementation HTTPHelper


+(id)PostUrlStr:(NSString *)urlStr parameters:(NSMutableDictionary *)parameters success:(ZXSuccessBlock)zxsuccessBlock
    failure:(ZXFailureBlock)zxfailureBlock{

    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager POST:urlStr parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"post responseObject = %@",responseObject);
        if (responseObject) {
            if (zxsuccessBlock) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                if (dic) {
                    zxsuccessBlock(dic);
                }
                NSLog(@"post result = %@%@",urlStr,dic);
            }
        }else NSLog(@"数据为空");

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"请求失败,重试%@",error);
    }];
    return nil;
}
+(id)GetHeadmutableRequest:(NSURLRequest *)request success:(ZXSuccessBlock)zxsuccessBlock
        failure:(ZXFailureBlock)zxfailureBlock{
    my_AppDelegate.isyididenglu = 1;
    if (!my_AppDelegate.isShow) {
        [SVProgressHUD show];
    }else{
        [SVProgressHUD dismiss];
    }
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        NSLog(@" http response : %ld",(long)httpResponse.statusCode);
        NSMutableDictionary * temDic = [NSMutableDictionary dictionary];
        [temDic setObject:@"50000" forKey:@"msgCod"];
        if ((long)httpResponse.statusCode == 401) {
             zxsuccessBlock(temDic);
            [SVProgressHUD showErrorWithStatus:@"用户名或密码错误"];
            return ;
        }else if ((long)httpResponse.statusCode == 403){
            [SVProgressHUD showErrorWithStatus:@"服务器拒绝请求"];
            zxsuccessBlock(temDic);
            return ;
        }
        else if ((long)httpResponse.statusCode == 404){
            zxsuccessBlock(temDic);
            [SVProgressHUD showErrorWithStatus:@"访问地址出错"];
            return ;
        }
        else if ((long)httpResponse.statusCode == 500){
            [SVProgressHUD showErrorWithStatus:@"服务器出现错误"];
            zxsuccessBlock(temDic);
            return ;
        }else if ((long)httpResponse.statusCode == 400){
            [SVProgressHUD showErrorWithStatus:@"登录状态出错"];
            zxsuccessBlock(temDic);
            return ;
        }
        else {
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        });
        [SVProgressHUD dismiss];
        if (!data||[data isEqual:[NSNull null]]) {
            zxsuccessBlock(temDic);
            return ;
        }
        if (data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSString * msgCodstring = [NSString stringWithFormat:@"%@",[dic objectForKey:@"msgCod"]];
            if ([msgCodstring isEqualToString:@"S0000"]) {
                
            }else if ([msgCodstring isEqualToString:@"S0001"]){
                zxsuccessBlock(temDic);
            }
            else{
                NSString * string = [dic objectForKey:@"message"];
                [SVProgressHUD showErrorWithStatus:string];
                dispatch_time_t delayTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0/*延迟执行时间*/ * NSEC_PER_SEC));
                
                dispatch_after(delayTime, dispatch_get_main_queue(), ^{
                    [SVProgressHUD dismiss];
                });
                BOOL ishengp = NO;
                
                if ([string isEqualToString:@"异地登录"]) {
                    for (NSInteger i=0; i<my_AppDelegate.roleArr.count; i++) {
                        int j = [my_AppDelegate.roleArr[i] intValue];
                        if (j == 0) {
                            ishengp = YES;
                        }
                    }
                    if (ishengp) {
                        my_AppDelegate.isyididenglu = 2;
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"backToLogin2" object:nil];
                    }else{
                        [[NSNotificationCenter defaultCenter]postNotificationName:@"backToLogin" object:nil];
                    }
                }
                zxsuccessBlock(temDic);
            }
            NSArray * arr = [dic objectForKey:@"data"];
            NSLog(@"temDic%@",dic);
            if (![arr isEqual:[NSNull null]]&&arr){
                zxsuccessBlock(dic);
            }else{
                return;
            }
        }
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"网络连接超时,请稍后"];
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            return;
        }
        [SVProgressHUD dismiss];

           }];
    // 启动任务
    [task resume];
    return nil;
}
+(id)PostmutableRequest:(NSURLRequest *)request success:(ZXSuccessBlock)zxsuccessBlock
                   failure:(ZXFailureBlock)zxfailureBlock{
    [SVProgressHUD show];
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    
    [SVProgressHUD show];
    NSURLSession *session = [NSURLSession sharedSession];
    NSURLSessionTask *task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
        NSLog(@" http response : %ld",(long)httpResponse.statusCode);
        if ((long)httpResponse.statusCode == 401) {
            [SVProgressHUD showErrorWithStatus:@"用户名或密码错误"];
            return ;
        }else if ((long)httpResponse.statusCode == 403){
            [SVProgressHUD showErrorWithStatus:@"服务器拒绝请求"];
            return ;
        }
        else if ((long)httpResponse.statusCode == 404){
            [SVProgressHUD showErrorWithStatus:@"访问地址出错"];
            return ;
        }
        else if ((long)httpResponse.statusCode == 500){
            [SVProgressHUD showErrorWithStatus:@"服务器出现错误"];
            return ;
        }
        else {
        }
        
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        [SVProgressHUD dismiss];
        if (!data||[data isEqual:[NSNull null]]) {
            return ;
        }
        if (data) {
            NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];
            NSArray * arr = [dic objectForKey:@"data"];
            if (![arr isEqual:[NSNull null]]&&arr){
                zxsuccessBlock(dic);
            }else{
                return;
            }
        }
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"网络连接超时,请稍后"];
            [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
            return;
        }
        [SVProgressHUD dismiss];
        
    }];
    // 启动任务
    [task resume];
    return nil;
}

+(id)GetUrlStr:(NSString *)urlStr parameters:(NSMutableDictionary *)parameters success:(ZXSuccessBlock)zxsuccessBlock
    failure:(ZXFailureBlock)zxfailureBlock{
    
    // 启动系统风火轮
    [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [manager GET:urlStr parameters:parameters progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        // 隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        NSLog(@"get responseObject = %@",responseObject);
        if (responseObject) {
            if (zxsuccessBlock) {
                NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableLeaves error:nil];
                if (dic) {
                    zxsuccessBlock(dic);
                }
                NSLog(@"get result = %@dic==/n%@",urlStr,dic);
            }
        }else NSLog(@"数据为空");
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        // 隐藏系统风火轮
        [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
        zxfailureBlock(error);
        NSLog(@"请求失败,重试");
    }];
    
        return nil;
}
- (NSDictionary *)dictionaryWithJsonString:(NSString *)jsonString {
    if (jsonString == nil) {
        return nil;
    }
    
    jsonString = [jsonString stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
    
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    NSError *err;
    NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:jsonData
                                                        options:NSJSONReadingMutableContainers
                                                          error:&err];
    if(err) {
        NSLog(@"json解析失败：%@",err);
        return nil;
    }
    return dic;
}

@end
